import { createApp } from 'app/config/app'
import Vue from 'vue'

const { app, router, store } = createApp()

if (window.__INITIAL_STATE__) {
  store.replaceState(window.__INITIAL_STATE__)
}

Vue.mixin({
  beforeRouteUpdate (to, from, next) {
    const { asyncData } = this.$options
    if (asyncData) {
      asyncData({
        store: this.$store,
        route: to
      }).then(next).catch(next)
    } else {
      next()
    }
  }
})

router.onReady(()=>{
	//添加路由钩子函数，用于处理 asyncData
	//在初始路由resolve后执行 以便不会二次预取(double-fetch) 已有数据/
	//使用 `router.beforeResolve()` 以便确保所有异步组件都resolve
	
	router.beforeResolve((to, from, next) => {
    const matched = router.getMatchedComponents(to)
    const prevMatched = router.getMatchedComponents(from)
		
		//找之前没有渲染组件，找出俩个匹配列表组件的差异
		let diffed = false
    const activated = matched.filter((c, i) => {
      return diffed || (diffed = (prevMatched[i] !== c))
    })
    if (!activated.length) {
      return next()
    }
		
		//如果这里有加载指示器(loading indicator) 就触发
		Promise.all(activated.map(c => {
      if (c.asyncData) {
        return c.asyncData({ store, route: to })
      }
    })).then(() => {
			//停止加载指示器(loadding indicator)
			next()
		}).catch(next)
	})
	app.$mount('#app')
})

